import com.sun.source.tree.Tree;

import java.util.*;

public class BinaryTree {

    static  class  TreeNode{
        public int val;

        public TreeNode left;//存储左孩子的引用
        public TreeNode right;//存储右孩子的引用

        public TreeNode(int val){
            this.val = val;
        }
    }

    public TreeNode createTree(){
        TreeNode one = new TreeNode(1);
        TreeNode two = new TreeNode(2);
        TreeNode three = new TreeNode(3);
        TreeNode four = new TreeNode(4);
        TreeNode five = new TreeNode(5);
        TreeNode six = new TreeNode(6);
        TreeNode seven = new TreeNode(7);
        TreeNode eight = new TreeNode(8);

        one.left = two;
        one.right = three;
        two.left = four;
        two.right = five;
        three.left = six;
        three.right = seven;
        five.right = eight;

        return one;
    }
    public int i;
    public TreeNode createTree2(String str){
        TreeNode root = null;
        if(str.charAt(i) != '#') {
            root = new TreeNode(str.charAt(i));
            i++;
            root.left = createTree2(str);
            root.right = createTree2(str);
        }else {
            i++;
        }
        return root;
    }

    //前序遍历
    public void preOrder(TreeNode root){
        if (root == null) return;
        System.out.print(root.val+" ");
        preOrder(root.left);
        preOrder(root.right);
    }

    //遍历思路
    //存储在一个表中
    List<Integer> list = new ArrayList<>();
    public List<Integer> preorderTraversal(TreeNode root){
        if (root == null) return list;
        list.add(root.val);
        preorderTraversal(root.left);
        preorderTraversal(root.right);
        return list;
    }
    //子问题
    public List<Integer> preorderTraversal2(TreeNode root){
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        list.add(root.val);

        List<Integer> leftTree = preorderTraversal2(root.left);
        list.addAll(leftTree);
        List<Integer> rightTree = preorderTraversal2(root.right);
        list.addAll(rightTree);

        return list;
    }

    //非递归前序遍历
    public void preOrderNor(TreeNode root){
        if (root == null) return;

        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        while(cur!=null || !stack.isEmpty()){
            while (cur!= null){
                stack.push(cur);
                System.out.print(cur.val +" ");
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
    }

    //中序遍历
    public void inOrder(TreeNode root){
        if (root == null) return;

        inOrder(root.left);
        System.out.println(root.val+" ");
        inOrder(root.right);
    }
    //遍历思路
    List<Integer> list1 = new ArrayList<>();
    public List<Integer> inorderTreversal(TreeNode root){
        if (root == null) return list1;
        inorderTreversal(root.left);
        list1.add(root.val);
        inorderTreversal(root.right);
        return list1;
    }
    //子问题
    public List<Integer> inorderTreversal1(TreeNode root){
        List<Integer> list1 = new ArrayList<>();
        if (root == null) return list1;

        List<Integer> leftTree = inorderTreversal1(root.left);
        list1.addAll(leftTree);
        list1.add(root.val);
        List<Integer> rightTree = inorderTreversal1(root.right);
        list1.addAll(rightTree);

        return list1;
    }

    //非递归中序遍历
    public void inOrderNor(TreeNode root){
        if (root == null) return;

        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        while(cur!=null || !stack.isEmpty()){
            while (cur!= null){
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            System.out.println(top.val + " ");
            cur = top.right;
        }
    }

    //后序遍历
    public void postOrder(TreeNode root){
        if (root == null) return;
        postOrder(root.left);
        postOrder(root.right);
        System.out.println(root.val+ " ");
    }
    //遍历思路
    List<Integer> list2 = new ArrayList<>();
    public List<Integer> postorderTreversal(TreeNode root){
        if (root == null) return list2;
        postorderTreversal(root.left);
        postorderTreversal(root.right);
        list2.add(root.val);
        return list2;
    }
    //子问题
    public List<Integer> postorderTreversal1(TreeNode root){
        List<Integer> list2 = new ArrayList<>();
        if (root == null) return list2;

        List<Integer> leftTree = postorderTreversal1(root.left);
        list2.addAll(leftTree);
        List<Integer> rightTree = postorderTreversal1(root.right);
        list2.addAll(rightTree);
        list2.add(root.val);
        return list2;
    }

    //非递归后续遍历
    public void postOrderNor(TreeNode root){
        if (root == null){
            return;
        }

        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;
        while(cur!= null || !stack.isEmpty()){
            while (cur!= null){
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            if (top.right==null ||top.right == prev){
                System.out.println(top.val + " ");
                stack.pop();
                prev = top;
            }else{
                cur = top.right;
            }
        }
    }

    public static int nodeSize = 0;
    //获取树结点的个数
    public void size(TreeNode root){
        if (root == null)return;
        nodeSize++;
        size(root.left);
        size(root.right);
    }

    public int size2(TreeNode root){
        if (root == null) return 0;

        return size2(root.left) + size2(root.right) + 1;
    }

    //获取叶子结点个数
    public static  int  leafSize = 0;
    public void getLeafNodeCount(TreeNode root){
        if (root == null) return;

        if (root.left == null && root.right == null){
            leafSize++;
        }

        getLeafNodeCount(root.left);
        getLeafNodeCount(root.right);
    }
    public int getLeafNodeCount2(TreeNode root) {
        if(root == null) {
            return 0;
        }
        if(root.left == null && root.right == null) {
            return 1;
        }
        return getLeafNodeCount2(root.left) +
                getLeafNodeCount2(root.right);
    }

    //第K层的结点个数
    public int getKLevelNodeCount(TreeNode root,int k){
        if (root == null) return 0;

        if (k == 1) return 1;

        return getKLevelNodeCount(root.left,k-1)+getKLevelNodeCount(root.right,k-1);
    }

    //获取树的高度
    public int getHeight(TreeNode root){
        if (root == null) return 0;

        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);

        return leftHeight > rightHeight ? leftHeight+1 :rightHeight+1;
    }

    //在树中查找元素
    public TreeNode findVal(TreeNode root,int val){
        if (root == null) return null;

        if (root.val == val) return root;

        TreeNode leftTree = findVal(root.left,val);
        if (leftTree != null) {
            return leftTree;
        }

        TreeNode rightTree = findVal(root.right,val);
        if (rightTree != null){
            return rightTree;
        }
        return null;
    }

    //判断是否同一颗树
    public boolean isSameTree(TreeNode p, TreeNode q){
        //首先先判断结构是否相同
        if (p!=null && q==null || p==null && q!=null){
            return false;
        }
        //上述if语句如果没有执行，意味着两个引用 同时为空或者同时不为空
        if (p == null && q == null){
            return true;
        }
        //如果都不为空，那么就判断数据是否相同
        if (p.val != q.val){
            return false;
        }

        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }

    //判断subRoot是否是root树的子树
    public boolean isSubTree(TreeNode root,TreeNode subRoot){
        if (root == null) return false;

        if (isSameTree(root,subRoot)) return true;

        if (isSubTree(root.left,subRoot)) return true;

        if (isSubTree(root.right,subRoot)) return true;

        return false;

    }

    //翻转二叉树
    public TreeNode invertTree(TreeNode root){
        if (root == null) return null;

        TreeNode tmp = root.left;
        root.left = root.right;
        root.right= tmp;
        invertTree(root.left);
        invertTree(root.right);
        return  root;
    }

    //判断是否对称二叉树
    public boolean isSymmetric(TreeNode root){
        if (root == null) return false;

        return isSymmetricChild(root.left,root.right);
    }

    public boolean isSymmetricChild(TreeNode leftTree ,TreeNode rightTree){
        if (leftTree !=null && rightTree == null || leftTree==null && rightTree!=null){//判断结构
            return false;
        }

        if (leftTree==null && rightTree==null){
            return true;
        }

        if (leftTree.val != rightTree.val){
            return false;
        }

        return isSymmetricChild(leftTree.left,rightTree.right) && isSymmetricChild(leftTree.right,rightTree.left);
    }


    //判断是否是平衡二叉树，每个结点都要判断 |left-right|<=1
    public boolean isBalanced(TreeNode root){
        if (root == null ) return  true;
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);

        return Math.abs(leftHeight-rightHeight) <2 && isBalanced(root.left) &&isBalanced(root.right);
    }

    public boolean isBalanced2(TreeNode root){
        if (root == null) return true;
        return getHeight2(root) >=0;
    }

    public int getHeight2(TreeNode root){
        if (root == null ) return 0;

        int leftHeight = getHeight2(root.left);
        if (leftHeight < 0) return -1;

        int rightHeight = getHeight2(root.right);
        if (rightHeight >0 && Math.abs(leftHeight-rightHeight) <=1){
            return Math.max(leftHeight,rightHeight) +1;
        }else{
            return -1;
        }
    }

    //二叉搜索树与双向链表//采用中序遍历二次搜索树就是排好序的
    TreeNode prev = null;

    public void ConvertChild(TreeNode root){
        if (root == null) return;
        ConvertChild(root.left);
        //打印
        root.left = prev;
        if (prev!=null){
            prev.right = root;
        }
        prev = root;
        ConvertChild(root.right);
    }
    public TreeNode Convert(TreeNode pRootOfTree){
        if (pRootOfTree == null) return null;
        ConvertChild(pRootOfTree);
        TreeNode head = pRootOfTree;
        if (head.left != null) head = head.left;

        return head;
    }

    //层序遍历
    public void levelOrder(TreeNode root){//用一个队列实现
        if (root == null) return;

        Queue<TreeNode> queue = new LinkedList<>();

        queue.offer(root);

        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();
            System.out.println(cur.val);
            if (cur.left!= null){
                queue.offer(cur.left);
            }
            if (cur.right!=null){
                queue.offer(cur.right);
            }
        }
    }

    //eg:1
    //   2 3
    //   4 5 6 7
    public  List<List<Integer>> levelOrder2(TreeNode root){
        List<List<Integer>> ret = new ArrayList<>();
        if (root == null) return ret;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()){
            List<Integer> list = new ArrayList<>();
            int size = queue.size();
            while(size!=0){
                TreeNode cur = queue.poll();
                list.add(cur.val);
                if (cur.left!= null){
                    queue.offer(cur.left);
                }
                if (cur.right!=null){
                    queue.offer(cur.right);
                }
                size--;
            }
            ret.add(list);
        }
        return ret;
    }

    public void levelOrder1(TreeNode root){//用一个队列实现
        if (root == null) return;

        Queue<TreeNode> queue = new LinkedList<>();

        queue.offer(root);

        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();
            System.out.println(cur.val);
            if (cur.left!= null){
                queue.offer(cur.left);
            }
            if (cur.right!=null){
                queue.offer(cur.right);
            }
        }
    }

    //判断一个树是不是完全二叉树
    public boolean isCompleteTree(TreeNode root){
        if (root == null) return true;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();
            if (cur!=null){
                queue.offer(cur.left);
                queue.offer(cur.right);
            }else{
                break;
            }
        }
        while(!queue.isEmpty()){
            TreeNode peek = queue.peek();
            if (peek != null){
                return false;
            }
            queue.poll();
        }
        return true;
    }

    //给定一个二叉树，找到给出两个结点的公共祖先
    public TreeNode lowestCommonAncestor(TreeNode root,TreeNode p,TreeNode q){
        if (root == null){
            return null;
        }

        if (root == p || root == q){
            return root;
        }

        TreeNode leftTree = lowestCommonAncestor(root.left,p,q);
        TreeNode rightTree = lowestCommonAncestor(root.right,p,q);

        if (leftTree!=null && rightTree!= null){
            return root;
        }else if(leftTree!=null){
            return leftTree;
        }else{
            return rightTree;
        }
    }


    //用两链表第一个交点的思路，用两个栈实现 前序遍历
    public boolean getPath(TreeNode root,TreeNode node,Stack<TreeNode> stack){
        if (root == null) return false;

        stack.push(root);
        if (root == node) return  true;

        boolean ret = getPath(root.left,node,stack);
        if (ret){
            return true;
        }
        ret = getPath(root.right,node,stack);
        if (ret){
            return true;
        }
        stack.pop();
        return false;
    }

    public TreeNode lowestCommonAncestor2(TreeNode root,TreeNode p,TreeNode q){
        if (root == null) return null;

        //获取q，p的路径
        Stack<TreeNode> stackP = new Stack<>();
        Stack<TreeNode> stackQ = new Stack<>();
        getPath(root,p,stackP);
        getPath(root,q,stackQ);

        //比较两个栈的大小
        int sizep = stackP.size();
        int sizeq = stackQ.size();
        if (sizep > sizeq){
            int size = sizep - sizeq;
            while(size != 0){
                stackP.pop();
                size--;
            }
        }else {
            int size = sizeq - sizep;
            while(size != 0){
                stackQ.pop();
                size--;
            }
        }

        //每次出数据，看栈顶元素是否相同
        while (!stackP.isEmpty() && !stackQ.isEmpty()){
            if (stackP.peek() == stackQ.peek()){
                return stackP.peek();
            }else{
                stackP.pop();
                stackQ.pop();
            }
        }
        return null;
    }

    //根据二叉树创建字符串
    public String tree2str(TreeNode root){
        if (root == null) return null;

        StringBuilder stringBuilder = new StringBuilder();
        tree2strChild(root,stringBuilder);
        return stringBuilder.toString();
    }

    public void tree2strChild(TreeNode t,StringBuilder stringBuilder){
        if (t == null) return;

        stringBuilder.append(t.val);

        if (t.left!=null){
            stringBuilder.append("(");
            tree2strChild(t.left,stringBuilder);
            stringBuilder.append(")");
        }else{
            if (t.right == null) return;
            else stringBuilder.append("()");
        }

        if (t.right!= null){
            stringBuilder.append("(");
            tree2strChild(t.right,stringBuilder);
            stringBuilder.append(")");
        }else{
            return;
        }
    }
}
